package org.ssp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.ssp.service.CoreService;
import org.ssp.util.MessageUtil;
import org.ssp.util.SignUtil;

import com.qq.weixin.mp.aes.AesException;


public class CoreServlet extends HttpServlet {
	private static Logger logger=Logger.getLogger(CoreServlet.class);
	private static final long serialVersionUID = 1L;
           
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("hello world");
		String signature=request.getParameter("signature");
		String timestamp=request.getParameter("timestamp");
		String nonce=request.getParameter("nonce");
		String echostr=request.getParameter("echostr");
		
		System.out.println("signature="+signature+"\ntimestamp="+timestamp+"\nnonce="+nonce+"\nechostr="+echostr);
		PrintWriter out=response.getWriter();

		if(SignUtil.checkSinature(signature, timestamp, nonce)){
			//响应内容给微信服务器
			out.write(echostr);
		}
		out.close();
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("dopost........");
		logger.info("请求进入到dopost方法");
		//编码设置
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		//请求校验
		String signature=request.getParameter("signature");
		String timestamp=request.getParameter("timestamp");
		String nonce=request.getParameter("nonce");
		//加解密类型
		String encryptType=request.getParameter("encrypt_type");
		PrintWriter out=response.getWriter();
		if(SignUtil.checkSinature(signature, timestamp, nonce)){
			
			//解析微信服务器发送的xml信息
			HashMap<String,String>requestMap=null;
			
			//加解密模式消息解析
			if("aes".equals(encryptType)){
				requestMap=MessageUtil.parseXMLCrypt(request);	
				String repXML=CoreService.processRequest(requestMap);
				try {
					repXML=MessageUtil.getWxEncrypt().encryptMsg(repXML, timestamp, nonce);
				} catch (AesException e) {
					e.printStackTrace();
				}
				out.write(repXML);
			}
			//明文模式消息解析
			else{
				System.out.println("明文模式");
				try {
					requestMap=MessageUtil.parseXML(request);
					String repXML=CoreService.processRequest(requestMap);
					out.write(repXML);
				} catch (Exception e) {
				}
			}			
		}
		out.close();
	}
}
